from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
#加载数据
x,y = datasets.load_iris(return_X_y=True)
#训练集测试集划分
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, stratify=y, random_state=0)
#创建网格搜索对象
estimator = KNeighborsClassifier()
param_grid = {'n_neighbors': [1, 3, 5, 7]}
estimator = GridSearchCV(estimator, param_grid, cv=5, verbose=0)
estimator.fit(x_train, y_train)
#打印最优参数
print('最优参数组合:',estimator.best_params_, '最好得分:',estimator.best_score_)
#测试集评估模型
print('测试集准确率:',estimator.score(x_test, y_test))

